#!usr/bin/env python
#coding=utf8

from tuangou.models.tuan_models import Item, ItemImage, Supplier, ItemLinkSupplier
from tuangou.common_logic import commutil

def get_supplier_list():
    return Supplier.objects.all()

def get_supply_list_by_page(page, page_size):
    page, page_size, offset = commutil.get_page_offset(page, page_size)
    supplys = Supplier.objects.all()[offset : offset + page_size]

    return supplys

def get_supply_count():
    return Supplier.objects.count()

def get_supply_by_id(id):
    try:
        supply = Supplier.objects.get(id=id)
    except:
        supply = None
        
    return supply

def save_supply(id, title):
    s = get_supply_by_id(id)
    if s:
        s.title = title
        s.save()

def add_supply(title):
    s = Supplier()
    s.title = title
    s.save()

def delete_supply(id):
    supply = get_supply_by_id(id)
    if supply:
        ItemLinkSupplier.objects.filter(supplier=supply.id).delete()
        supply.delete()

def get_item_list(supply_id, page, page_size, order_by):
    page, page_size, offset = commutil.get_page_offset(page, page_size)
    supply = get_supply_by_id(supply_id)
    items = []
    item_count = 0
    if supply:
        item_count = supply.items.count()
        items = supply.items.order_by(order_by)[offset : offset + page_size]
        for item in items:
            item.price = commutil.decimalFormat(item.price)
            item.tuanprice = commutil.decimalFormat(item.tuanprice)
            try:
                item.homeimage = item.itemimage_set.filter(imagetype='home')[0]
            except:
                item.homeimage = ItemImage(thumburl='', imagetype='home', originalurl='')
    return items, item_count





    
    